package com.example.bingobox.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

public class NetworkSelector extends View {
    private Paint textPaint;
    private Paint dotPaint;
    private int viewWidth;
    private int viewHeight;
    private static final float DOT_RADIUS = 8;  // 状态点的半径
    private static final int DOT_MARGIN = 10;   // 状态点和文字之间的间距
    private static final String[] NETWORK_STATUS = {"无网络", "WIFI", "移动数据"};
    private String currentStatus = "";
    private final Rect textBounds = new Rect();
    private ConnectivityManager connectivityManager;
    private ConnectivityManager.NetworkCallback networkCallback;

    public NetworkSelector(Context context) {
        super(context);
        init();
    }

    public NetworkSelector(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Paint.Align.LEFT);
        float textSizeInPx = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            16,  // 稍微大一点的字号
            getResources().getDisplayMetrics()
        );
        textPaint.setTextSize(textSizeInPx);

        dotPaint = new Paint();
        dotPaint.setAntiAlias(true);

        setupNetworkCallback();
    }

    private int getStatusColor(String status) {
        switch (status) {
            case "无网络":
                return Color.rgb(200, 0, 0);    // 红色
            case "WIFI":
                return Color.rgb(50, 205, 50);  // 绿色
            case "移动数据":
                return Color.rgb(255, 165, 0);  // 橙色
            default:
                return Color.GRAY;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (!currentStatus.isEmpty()) {
            // 计算文字大小
            textPaint.getTextBounds(currentStatus, 0, currentStatus.length(), textBounds);
            
            // 绘制状态点
            dotPaint.setColor(getStatusColor(currentStatus));
            float centerY = viewHeight / 2f;
            canvas.drawCircle(DOT_RADIUS, centerY, DOT_RADIUS, dotPaint);
            
            // 绘制文字
            float textX = 2 * DOT_RADIUS + DOT_MARGIN;
            float textY = centerY + textBounds.height() / 2f;
            canvas.drawText(currentStatus, textX, textY, textPaint);
        }
    }

    private void setupNetworkCallback() {
        connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        
        NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .build();

        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                updateNetworkStatus();
            }

            @Override
            public void onLost(Network network) {
                updateNetworkStatus();
            }

            @Override
            public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
                updateNetworkStatus();
            }
        };

        connectivityManager.registerNetworkCallback(request, networkCallback);
        updateNetworkStatus();
    }

    private void updateNetworkStatus() {
        if (connectivityManager == null) {
            setNetworkStatus("无网络");
            return;
        }

        NetworkCapabilities capabilities;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Network activeNetwork = connectivityManager.getActiveNetwork();
            if (activeNetwork == null) {
                setNetworkStatus("无网络");
                return;
            }
            capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
        } else {
            @SuppressWarnings("deprecation")
            android.net.NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
                setNetworkStatus("无网络");
                return;
            }
            
            @SuppressWarnings("deprecation")
            boolean isWifi = activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;
            @SuppressWarnings("deprecation")
            boolean isMobile = activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            
            if (isWifi) {
                setNetworkStatus("WIFI");
            } else if (isMobile) {
                setNetworkStatus("移动数据");
            } else {
                setNetworkStatus("无网络");
            }
            return;
        }

        if (capabilities == null) {
            setNetworkStatus("无网络");
            return;
        }

        boolean hasWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
        boolean hasCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);

        if (hasWifi) {
            setNetworkStatus("WIFI");
        } else if (hasCellular) {
            setNetworkStatus("移动数据");
        } else {
            setNetworkStatus("无网络");
        }
    }

    private void setNetworkStatus(String status) {
        currentStatus = status;
        post(this::invalidate);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (connectivityManager != null && networkCallback != null) {
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
    }
} 